package com.bittech.client.service;

import javax.swing.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @Author: yuisama
 * @Date: 2019-06-15 13:19
 * @Description:群聊界面
 */
public class GroupChatGUI {
    // 群聊名称标题
    private String title;
    // 群好友名称
    private List<String> membersName;
    // 发送者名称
    private String myName;
    private Connect2Server connect2Server;
    private JPanel groupChatMainPanel;
    private JTextField out2Server;
    private JTextArea readFromServer;
    private JList memberNames;
    // 群聊界面主Frame
    private JFrame frame;
    private PrintStream outStream;

    public GroupChatGUI(String title, List<String> membersName, String myName,Connect2Server connect2Server) {
        this.connect2Server = connect2Server;
        this.title = title;
        this.membersName = membersName;
        this.myName = myName;
        try {
            outStream = new PrintStream(connect2Server.getClientWrite(),true,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 加载群聊好友名称
        DefaultListModel<String> defaultListModel = new DefaultListModel<>();
        for (String str : membersName)
            defaultListModel.addElement(str);
        memberNames.setModel(defaultListModel);
        frame = new JFrame(title);
        frame.setContentPane(groupChatMainPanel);
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frame.setSize(400,400);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        // 捕捉TextField回车事件，刷新到TextArea并发送到服务端
        out2Server.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                StringBuilder sb = new StringBuilder();
                sb.append(out2Server.getText());
                // 敲下回车
                // 刷新TextArea并发送到服务端
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    String str = sb.toString();
                    // G:groupName_myName-msg
                    String out2ServerStr = "G:"+title+"_"+myName+"-"+str;
                    System.out.println("群聊发送到服务器的信息为"+out2ServerStr);
                    outStream.println(out2ServerStr);
                    out2Server.setText("");
                }
            }
        });
    }

    public void readFromServer(String msg) {
        System.out.println("收到服务器发来的群聊信息"+msg);
        readFromServer.append(msg+"\n");
    }

    public JFrame getFrame() {
        return frame;
    }
}
